import requests
import json
import os
import re
import time
from datetime import datetime, timedelta
from urllib.parse import urlparse

# 创建以当前日期命名的文件夹
current_date = datetime.now().strftime('%Y%m%d')
os.makedirs(current_date, exist_ok=True)

# 请求URL
url = "http://www.didano.cn/wechat_v2/base/dectection/post/findStudentDetection?from=xiaonuo-vue&oriId=gh_98d50f853359&sid=881&stoken=NWFiODczYWM4YjVjNTdmYjliMjgwYjVkYTVmOTZjMTEjMTc1OTc1Mjg0MjcxMyMzMTUzNjAwMCNPRGd4"

# 请求头
headers = {
    "Content-Type": "application/json",
    "Accept": "application/json, text/plain, */*",
    "uid": "NTAwMzg2ZGE5ODRiZmY3YTVmNmE3MzYyYzFkN2FlNjcjMTc1OTc1Mjg0MjUwMiMzMTUzNjAwMCNiMVp1Ym5aMk1FNW1kSGhITjJOdlUxcHJTazgxY3poWlREZFFadz09",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 NetType/WIFI MicroMessenger/6.8.0(0x16080000) MacWechat/3.8.10(0x13080a10) XWEB/1227 Flue",
    "history": "1",
    "Origin": "http://www.didano.cn",
    "Referer": "http://www.didano.cn/wechat_v2/structure/babycenter?oriid=gh_98d50f853359&code=0113Yb0w3T1WK53wcy0w3wvm6k43Yb0V&state=STATE",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Cookie": "_bl_uid=7jm6OgtwdgUsy5iwUuj5aa1y3eX1; JSESSIONID=29E06C45953CC5CA5E1BF001DBD5A8E7; Hm_lvt_58ca8a466c9ff30741e55bc241397c61=1759674096,1759740931,1759751662; HMACCOUNT=B153D88ADDDAB29A; Hm_lpvt_58ca8a466c9ff30741e55bc241397c61=1759752843; SERVERID=95ffc6cb916c31eb43cab78ea85b12b7|1759752958|1759752833"
}

# 定义寒暑假时间范围
vacation_periods = [
    (datetime.strptime("2023-01-01", "%Y-%m-%d"), datetime.strptime("2023-02-01", "%Y-%m-%d")),
    (datetime.strptime("2023-07-08", "%Y-%m-%d"), datetime.strptime("2023-08-31", "%Y-%m-%d")),
    (datetime.strptime("2024-01-27", "%Y-%m-%d"), datetime.strptime("2024-02-26", "%Y-%m-%d")),
    (datetime.strptime("2024-07-08", "%Y-%m-%d"), datetime.strptime("2024-08-31", "%Y-%m-%d")),
    (datetime.strptime("2025-01-11", "%Y-%m-%d"), datetime.strptime("2025-02-16", "%Y-%m-%d"))
]

def is_vacation_date(date):
    """检查日期是否在寒暑假期间"""
    for start, end in vacation_periods:
        if start <= date <= end:
            return True
    return False

# 日期范围
start_date = datetime.strptime("2022-9-1", "%Y-%m-%d")
end_date = datetime.strptime("2025-07-20", "%Y-%m-%d")

# 学生ID
student_id = 524273

# 遍历日期范围
current = start_date
while current <= end_date:
    # 检查是否为寒暑假日期
    if is_vacation_date(current):
        print(f"跳过寒暑假日期: {current.strftime('%Y-%m-%d')}")
        current += timedelta(days=1)
        continue
    
    date_str = current.strftime("%Y-%m-%d")
    print(f"正在处理日期: {date_str}")
    
    # 请求体
    payload = {
        "date": date_str,
        "studentId": student_id
    }
    
    try:
        # 发送POST请求
        response = requests.post(url, headers=headers, data=json.dumps(payload), timeout=30)
        response.raise_for_status()  # 如果响应状态码不是200会抛出异常
        
        # 解析响应
        result = response.json()
        
        if result.get("success") and result.get("data") and result["data"].get("detection"):
            detection_data = result["data"]["detection"]
            
            # 遍历检测数据
            for item in detection_data:
                org_img_url = item.get("orgImgUrl")
                if org_img_url:
                    # 使用正则表达式提取.jpg之前的部分（去除查询参数）
                    match = re.match(r'(.*?\.jpg)', org_img_url)
                    if match:
                        clean_img_url = match.group(1)
                    else:
                        clean_img_url = org_img_url
                    
                    # 提取文件名
                    # 从URL中提取时间戳部分
                    created_time = item.get("created", "").replace(" ", "").replace(":", "")
                    if created_time:
                        filename = f"{student_id}_{created_time}.jpg"
                    else:
                        # 从URL中提取文件名
                        parsed_url = urlparse(clean_img_url)
                        filename = os.path.basename(parsed_url.path)
                    
                    # 构造保存路径
                    save_path = os.path.join(current_date, filename)
                    
                    # 检查文件是否已存在
                    if os.path.exists(save_path):
                        print(f"  文件已存在，跳过: {filename}")
                        continue
                    
                    # 下载图片
                    print(f"  正在下载图片: {filename}")
                    img_response = requests.get(clean_img_url, timeout=30)
                    img_response.raise_for_status()
                    
                    # 保存图片
                    with open(save_path, "wb") as f:
                        f.write(img_response.content)
                    
                    print(f"  ✓ 已保存图片: {filename}")
                else:
                    print(f"  日期 {date_str} 没有图片URL")
        else:
            print(f"  日期 {date_str} 没有检测数据")
            
    except requests.exceptions.RequestException as e:
        print(f"  请求失败 {date_str}: {e}")
    except Exception as e:
        print(f"  处理日期 {date_str} 时出错: {e}")
    
    # 间隔3秒进行下一次请求
    print("  等待3秒...")
    time.sleep(3)
    
    # 移动到下一个日期
    current += timedelta(days=1)

print(f"\n所有图片已保存到 {current_date} 文件夹中")